define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var realscene_id = Fast.api.query('realscene_id');
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'newhouse/realscenelist/index' + location.search,
                    add_url: 'newhouse/realscenelist/add',
                    addplus_url: 'newhouse/realscenelist/addplus',
                    edit_url: 'newhouse/realscenelist/edit',
                    del_url: 'newhouse/realscenelist/del',
                    multi_url: 'newhouse/realscenelist/multi',
                    table: 'newhouse_realscene_list',
                }
            });

            var table = $("#table");
            Template.helper("Moment", Moment);
            Template.helper("cdnurl", Fast.api.cdnurl);

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                templateView: true,
                pageSize: 12,
                queryParams: function (params) {
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    if (realscene_id) {
                        filter['realscene_id'] = realscene_id;
                    }
                    params.filter = JSON.stringify(filter);
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'image', title: __('Image'), events: Table.api.events.image, formatter: Controller.api.formatter.image},
                        {field: 'weigh', title: __('Weigh')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'admin.nickname', title: __('Admin.nickname')},
                        {field: 'newhouserealscene.title', title: __('Newhouserealscene.title')},
                        {field: 'newhouserealscene.path', title: __('Newhouserealscene.path')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                search: realscene_id?false:true
            });

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                if (realscene_id) {
                    $(".columns-right").hide();
                }

                // 拖拽排序
                setTimeout(function () {
                    $(".row-flex").attr('id', 'sortrank');

                    if ($('#sortrank', table).find("input[type='checkbox'][data-index]").size() > 0) {
                        // 挺拽选择,需要重新绑定事件
                        require(['drag', 'drop'], function () {
                            $('#sortrank', table).drag("start", function (ev, dd) {
                                return $('<div class="selection" />').css('opacity', .65).appendTo(document.body);
                            }).drag(function (ev, dd) {
                                $(dd.proxy).css({
                                    top: Math.min(ev.pageY, dd.startY),
                                    left: Math.min(ev.pageX, dd.startX),
                                    height: Math.abs(ev.pageY - dd.startY),
                                    width: Math.abs(ev.pageX - dd.startX)
                                });
                            }).drag("end", function (ev, dd) {
                                $(dd.proxy).remove();
                            });
                            $(Table.config.firsttd, table).drop("start", function () {
                                Table.api.toggleattr(this);
                            }).drop(function () {
                                Table.api.toggleattr(this);
                            }).drop("end", function () {
                                Table.api.toggleattr(this);
                            });
                            $.drop({
                                multi: true
                            });
                        });
                    }

                    // 拖拽排序
                    $('#sortrank', table).dragsort({
                        itemSelector: 'div:visible',
                        dragSelector: "a.btn-dragsort",
                        dragEnd: function (a, b) {
                            var element = $("a.btn-dragsort", this);
                            var data = table.bootstrapTable('getData');
                            var current = data[parseInt($(this).data("index"))];
                            var options = table.bootstrapTable('getOptions');

                            //改变的值和改变的ID集合
                            var ids = $.map($("div.col-sm-4", table), function (tr) {
                                return data[parseInt($(tr).data("index"))][options.pk];
                            });
                            var changeid = current[options.pk];
                            var pid = typeof current.pid != 'undefined' ? current.pid : '';
                            var params = {
                                url: table.bootstrapTable('getOptions').extend.dragsort_url,
                                data: {
                                    ids: ids.join(','),
                                    changeid: changeid,
                                    pid: pid,
                                    field: Table.config.dragsortfield,
                                    orderway: options.sortOrder,
                                    table: options.extend.table
                                }
                            };
                            Fast.api.ajax(params, function (data, ret) {
                                var success = $(element).data("success") || $.noop;
                                if (typeof success === 'function') {
                                    if (false === success.call(element, data, ret)) {
                                        return false;
                                    }
                                }
                                table.bootstrapTable('refresh');
                            }, function (data, ret) {
                                var error = $(element).data("error") || $.noop;
                                if (typeof error === 'function') {
                                    if (false === error.call(element, data, ret)) {
                                        return false;
                                    }
                                }
                                table.bootstrapTable('refresh');
                            });
                        },
                        placeHolderTemplate: "<div></div>"
                    });
                }, 300);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            var parenttable = table.closest('.bootstrap-table');
            var options = table.bootstrapTable('getOptions');
            var toolbar = $(options.toolbar, parenttable);
            $(toolbar).off('click', Table.config.addbtn);
            $(toolbar).on('click', Table.config.addbtn, function () {
                var ids = Table.api.selectedids(table);
                var url = options.extend.add_url;
                if (url.indexOf("{ids}") !== -1) {
                    url = Table.api.replaceurl(url, {ids: ids.length > 0 ? ids.join(",") : 0}, table);
                }
                if (realscene_id !== null) {
                    url = url + '?realscene_id=' + realscene_id;
                }
                Fast.api.open(url, __('Add'), $(this).data() || {});
            });
            $(toolbar).on('click', '.btn-addplus', function () {
                var ids = Table.api.selectedids(table);
                var url = options.extend.addplus_url;
                if (url.indexOf("{ids}") !== -1) {
                    url = Table.api.replaceurl(url, {ids: ids.length > 0 ? ids.join(",") : 0}, table);
                }
                if (realscene_id !== null) {
                    url = url + '?realscene_id=' + realscene_id;
                }
                Fast.api.open(url, __('批量管理'), $(this).data() || {});
            });
        },
        add: function () {
            if (realscene_id !== null) {
                $('#c-realscene_id').val(realscene_id);
            }
            Controller.api.bindevent();
        },
        addplus: function () {
            if (realscene_id !== null) {
                $('#c-realscene_id').val(realscene_id);
            }
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

                var input_id = $('#plupload-image').data("input-id") ? $('#plupload-image').data("input-id") : "";
                var preview_id = $('#plupload-image').data("preview-id") ? $('#plupload-image').data("preview-id") : "";
                if (preview_id) {
                    $(document.body).off("click", "#" + preview_id + " .btn-trash");
                    // 监听事件
                    $("#plupload-image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + preview_id + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + preview_id + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/realscenelist/delUpload',
                                    data: {
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    if (input_id) {
                                        $("#" + input_id).val('');
                                    }
                                    that.closest("li").remove();
                                    $("#plupload-image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if (input_id) {
                    if ($("#" + input_id).val() != '') {
                        $("#plupload-image").hide();
                    }
                }
            },
            formatter: {
                image: function (value, row, index) {
                    value = value ? Fast.api.cdnurl(value) : '/assets/img/blank.gif';
                    var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
                    return '<a href="javascript:void(0);"><img class="' + classname + '" src="' + value + '" /></a>';
                }
            }
        }
    };
    return Controller;
});
